package com.example.base.repository

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.example.base.entity.Rest
import com.example.base.entity.RestNoData
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 * MVVM Model 层基类
 */
abstract class BaseRepository {

    /**
     * 异步处理数据
     * @param requestResult 实际需要异步处理的请求
     */
    suspend fun <Data> request(requestResult: suspend () -> Rest<Data>) =
        withContext(Dispatchers.IO) {
            val result = requestResult()

            suspendCoroutine<Rest<Data>> { continuation ->
                // Catch Exception Custom
                // continuation.resumeWithException(NullPointerException("test e!"))

                continuation.resume(result)
            }
        }

    /**
     * 异步处理数据
     * @param requestResult 实际需要异步处理的请求
     */
    suspend fun <Data> requestNoData(requestResult: suspend () -> RestNoData<Data>) =
        withContext(Dispatchers.IO) {
            val result = requestResult()

            suspendCoroutine<RestNoData<Data>> { continuation ->
                // Catch Exception Custom
                // continuation.resumeWithException(NullPointerException("test e!"))

                continuation.resume(result)
            }
        }


}